<template>
  <page-header-wrapper>
    <a-card :bordered="false">
      <div class="table-page-search-wrapper">
        <a-form layout="inline">
          <a-row :gutter="48">
            <a-col :md="8" :sm="24">
              <a-form-item label="用户状态">
                <a-select v-model="queryParam.status" placeholder="请选择" default-value="0">
                  <a-select-option value="0">全部</a-select-option>
                  <a-select-option value="1">关闭</a-select-option>
                  <a-select-option value="2">运行中</a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :md="8" :sm="24">
              <span class="table-page-search-submitButtons">
                <a-input-search v-model="queryParam.search" placeholder="请输入关键字查询" enter-button="查询" @search="$refs.table.refresh(true)"/>
                <a-button style="margin-left: 8px" @click="() => this.queryParam = {}">重置</a-button>
              </span>
            </a-col>
          </a-row>
        </a-form>
      </div>

      <!--表格上部操作-->
      <div class="table-operator">
        <a-button v-action:add type="primary" icon="plus" @click="handleAdd">新建</a-button>
        <a-button v-action:update v-if="selectedRowKeys.length > 0" type="primary" icon="delete" @click="handleAdd">删除</a-button>
        <a-button v-action:update v-if="selectedRowKeys.length > 0" type="primary" icon="lock" @click="handleAdd">锁定</a-button>
      </div>

      <s-table
        ref="table"
        size="default"
        rowKey="id"
        :columns="columns"
        :data="loadData"
        :alert="true"
        :rowSelection="rowSelection"
        showPagination="auto"
      >
        <!--状态插槽-->
        <span slot="status" slot-scope="text">
          <a-tag :color="text | statusFilter">{{ text }}</a-tag>
        </span>
        <!--操作插槽-->
        <span slot="action" slot-scope="text, record">
          <template>
            <a @click="handleEdit(record)" icon="edit">编辑</a>
            <a-divider type="vertical"/>
            <a @click="handleSub(record)">删除</a>
            <a-divider type="vertical"/>
            <a @click="handleSub(record)">锁定</a>
          </template>
        </span>
      </s-table>

      <create-form
        ref="createModal"
        :visible="visible"
        :loading="confirmLoading"
        :model="mdl"
        :data="loadResource"
        @cancel="handleCancel"
        @ok="handleOk"
      />
      <step-by-step-modal ref="modal" @ok="handleOk"/>
    </a-card>
  </page-header-wrapper>
</template>

<script>
import { Ellipsis, STable } from '@/components'
import { getRoleList, saveOrUpdate } from '@/api/role'

import StepByStepModal from './modules/StepByStepModal'
import CreateForm from './modules/CreateForm'
import { columns } from '@/views/role/constant'
import { STATUS_MAP } from '@/constants/commonConstant'
import { loadResourceTree } from '@/api/resource'

export default {
  name: 'RoleList',
  components: {
    STable,
    Ellipsis,
    CreateForm,
    StepByStepModal
  },
  data() {
    this.columns = columns
    return {
      // create model
      visible: false,
      confirmLoading: false,
      mdl: null,
      // 高级搜索 展开/关闭
      advanced: false,
      // 查询参数
      queryParam: {},
      // 加载数据方法 必须为 Promise 对象
      loadData: parameter => {
        const requestParameters = Object.assign({}, parameter, this.queryParam)
        return getRoleList(requestParameters).then(res => {
          return res.result
        })
      },
      selectedRowKeys: [],
      selectedRows: [],
      loadResource: () => {
        return loadResourceTree().then(response => {
          if (response.success) {
            return response.result
          } else {
            this.$message.error(response.message || '数据获取失败')
            return []
          }
        }).catch(error => {
          this.$message.error((error && error.message) || '数据获取失败')
        })
      }
    }
  },
  filters: {
    statusFilter(type) {
      return STATUS_MAP[type]
    }
  },
  computed: {
    rowSelection() {
      return {
        selectedRowKeys: this.selectedRowKeys,
        onChange: this.onSelectChange
      }
    }
  },
  methods: {
    handleAdd() {
      this.mdl = null
      this.visible = true
    },
    handleEdit(record) {
      this.visible = true
      this.mdl = { ...record }
    },
    handleOk() {
      const form = this.$refs.createModal.form
      this.confirmLoading = true
      form.validateFields((errors, values) => {
        if (!errors) {
          const isUpdate = values.id > 0
          values.id = isUpdate ? values.id : null
          saveOrUpdate(values).then(response => {
            if (response.success) {
              this.visible = false
              this.confirmLoading = false
              // 重置表单数据
              form.resetFields()
              // 刷新表格
              this.$refs.table.refresh()
              this.$message.info(isUpdate ? '修改成功' : '新增成功')
            }
          })
        } else {
          this.confirmLoading = false
        }
      })
    },
    handleCancel() {
      this.visible = false
      const form = this.$refs.createModal.form
      form.resetFields() // 清理表单数据（可不做）
    },
    handleSub(record) {
      if (record.status !== 0) {
        this.$message.info(`${ record.no } 订阅成功`)
      } else {
        this.$message.error(`${ record.no } 订阅失败，规则已关闭`)
      }
    },
    onSelectChange(selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectedRows = selectedRows
    }
  }
}
</script>
